import base64
import json
import smtplib
from email.header import Header
from email.mime.text import MIMEText

from baidusearch.baidusearch import search

import requests
import urllib.parse
import requests
from io import BytesIO
from docx import Document
import re
from rest_framework.views import APIView

from tools.config import boss_url, new_city, boss_job
# from selenium import webdriver
# from selenium.webdriver.chrome.options import Options
# from selenium.webdriver.support.ui import WebDriverWait
# from selenium.webdriver.common.by import By
# from selenium.webdriver.support import expected_conditions as EC
from tools.ocr import *

class SendMail:

    def send_email(self, sender, password, receiver, subject, text, smtp_server='smtp.qq.com', smtp_port=587):
        """
        发送邮件的函数

        参数：
        sender (str): 发件人邮箱地址
        password (str): 发件人邮箱的授权码（或密码，但一般使用授权码）
        receiver (str or list): 收件人邮箱地址，可以是单个邮箱地址字符串，或包含多个收件人邮箱的列表
        subject (str): 邮件主题
        text (str): 邮件正文内容
        smtp_server (str): SMTP服务器地址，默认是QQ邮箱的SMTP服务器
        smtp_port (int): SMTP服务器端口，默认是587（TLS）

        返回：
        None
        """
        # 创建一个MIMEText对象，设置邮件内容、格式（纯文本）以及编码
        msg = MIMEText(text, 'plain', 'utf-8')
        # 设置邮件的主题、发件人、收件人信息
        msg['Subject'] = Header(subject, 'utf-8')
        msg['From'] = sender
        if isinstance(receiver, list):
            msg['To'] = ','.join(receiver)
        else:
            msg['To'] = receiver

        try:
            # 创建SMTP对象，连接到SMTP服务器
            server = smtplib.SMTP(smtp_server, smtp_port)
            # 显式指定编码为 'UTF-8'，解决可能出现的编码问题
            server.command_encoding = 'utf-8'
            # 启动TLS加密（如果SMTP服务器支持）
            server.starttls()
            # 登录发件人邮箱
            server.login(sender, password)
            # 发送邮件
            server.sendmail(sender, receiver, msg.as_string())
            print('邮件发送成功')
            return True
        except smtplib.SMTPException as e:
            print('邮件发送失败，错误原因：', e)
            return False


class Search:

    def baidu(self, word):
        results = search(word)  # 返回10个或更少的结果
        for result in results:
            print(result['title'], result['url'])
        return results


# class Boss:
#
#     def salary(self, url):
#         options = Options()
#         options.headless = True
#         driver = webdriver.Chrome(options=options)
#         try:
#             driver.get(url)
#             wait = WebDriverWait(driver, 10)
#             class_name_to_remove = 'm-friend-link'  # 请替换为您要删除的 class_name
#             remove_elements_js = f"""
#                 var elements = document.getElementsByClassName('{class_name_to_remove}');
#                 while(elements.length > 0) {{
#                     elements[0].parentNode.removeChild(elements[0]);
#                 }}
#                 """
#             driver.execute_script(remove_elements_js)
#             element = wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'salary-chart')))
#             data = element.text
#             return data
#         finally:
#             driver.quit()
#
#     def search(self, url):
#         options = Options()
#         options.headless = True
#         driver = webdriver.Chrome(options=options)
#         try:
#             driver.get(url)
#             wait = WebDriverWait(driver, 10)
#             element = wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'job-list-box')))
#             data = element.text
#             return data
#         finally:
#             driver.quit()




class Word:

    def get_word_city(self, city):
        for i, k in new_city.items():
            if i in city or city in i:
                return k
        return False

    def get_word_job(self, job):
        for k, v in boss_job.items():
            if k.lower() in job.lower() or job.lower() in k.lower():
                return v
        return False

class OCRToll(APIView):
    def check_url_content(self, url):
        try:
            # 使用 GET 请求获取前 512 个字节
            response = requests.get(url)
            content_type = response.headers.get('Content-Type', '').lower()
            if 'application/pdf' in content_type:
                return self.ocr_pdf(response.content)
            elif 'image' in content_type:
               return self.ocr_image(url)
            else:
                document = fetch_word_from_url(url)
                text_content = extract_text_from_doc(document)
                filtered_text = filter_text_lines(text_content)
                return filtered_text
        except requests.exceptions.RequestException as e:
            print(f"An error occurred: {e}")

    def ocr_image(self,url):
        content = AipOcr('116848380','CR5o9HRmsPqeVtTEeIqVpNDV', 'wkgMnBrWjSCCEhgRy6UfGZegYe7VGcR8').basicGeneralUrl(url)
        words = ''
        for k in content['words_result']:
            words += k['words']

        return words

    def ocr_pdf(self, url):
        content = AipOcr('116848380','CR5o9HRmsPqeVtTEeIqVpNDV', 'wkgMnBrWjSCCEhgRy6UfGZegYe7VGcR8').basicGeneralPdf(url)
        words = ''
        for k in content['words_result']:
            if is_meaningful(k['words']):
                words += k['words'] + '\n'
        return words



def is_meaningful(text):
    # 去除空白字符
    text = text.strip()
    # 如果字符串为空，返回 False
    if not text:
        return False
    # 特殊符号列表，可以根据需要扩展
    special_symbols = set('~!@#$%^&*()-_=+[]{}|;:\'",.<>?/`•—…￥《》')
    # 如果字符串全部由特殊符号组成，返回 False
    if all(char in special_symbols for char in text):
        return False
    # 检查是否含有中文字符
    if re.search(r'[\u4e00-\u9fff]', text):
        return True
    # 检查是否含有英文字符
    elif re.search(r'[A-Za-z]', text):
        # 根据长度判断
        if len(text) <= 20:
            return True
        else:
            return False
    else:
        # 不含中文和英文的情况下，判断长度
        if len(text) <= 5:
            return True
        else:
            return False


def fetch_word_from_url(url):
    """
    从指定的 URL 获取 Word 文件，并返回文档对象。
    """
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)'
                      'Chrome/58.0.3029.110 Safari/537.3',
        'Accept': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    }
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        content_type = response.headers.get('Content-Type', '')
        if 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' in content_type:
            # 将下载的内容放入内存字节流中
            file_stream = BytesIO(response.content)
            # 使用 python-docx 打开 Word 文档
            try:
                document = Document(file_stream)
                return document
            except Exception as e:
                # 如果解析失败，保存文件以便调试
                with open('debug.docx', 'wb') as f:
                    f.write(response.content)
                raise Exception(f"无法解析 Word 文档。已将文件保存到 'debug.docx'。错误信息：{e}")
        else:
            # 保存内容以便调试
            with open('debug_content', 'wb') as f:
                f.write(response.content)
            raise Exception(
                f"Content-Type 非预期的 Word 文档类型，实际为：{content_type}。已将内容保存到 'debug_content'。")
    else:
        raise Exception(f"无法从 URL 获取 Word 文件，状态码：{response.status_code}")


def extract_text_from_doc(document):
    """
    从 Word 文档对象中提取所有文字内容，包括段落和表格。
    """
    full_text = []

    # 提取段落中的文字
    for para in document.paragraphs:
        text = para.text.strip()
        if text:
            full_text.append(text)

    # 提取表格中的文字
    for table in document.tables:
        for row in table.rows:
            row_data = []
            for cell in row.cells:
                cell_text = []
                for paragraph in cell.paragraphs:
                    cell_paragraph_text = paragraph.text.strip()
                    if cell_paragraph_text:
                        cell_text.append(cell_paragraph_text)
                if cell_text:
                    row_data.append(' '.join(cell_text))
            if row_data:
                full_text.append(' | '.join(row_data))

    return '\n'.join(full_text)


def is_meaningful(text):
    """
    判断文本是否是有意义的内容。
    """
    # 去除空白字符
    text = text.strip()
    # 如果字符串为空，返回 False
    if not text:
        return False
    # 特殊符号列表，可以根据需要扩展
    special_symbols = set('~!@#$%^&*()-_=+[]{}|;:\'",.<>?/`•—…￥《》')
    # 如果字符串全部由特殊符号组成，返回 False
    if all(char in special_symbols for char in text):
        return False
    # 检查是否含有中文字符
    if re.search(r'[\u4e00-\u9fff]', text):
        return True
    # 检查是否含有英文单词
    elif re.search(r'[A-Za-z]', text):
        # 根据长度判断
        if len(text) <= 20:
            return True
        else:
            return False
    else:
        # 不含中文和英文的情况下，判断长度
        if len(text) <= 5:
            return True
        else:
            return False


def filter_text_lines(text_content):
    """
    对提取的文本内容按行进行过滤，保留有意义的内容。
    """
    lines = text_content.split('\n')
    meaningful_lines = [line for line in lines if is_meaningful(line)]
    return '\n'.join(meaningful_lines)

